// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-18

package middlewares

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/result"
	"gitee.com/go-wares/framework-iris/framework/src/middlewares"
	"github.com/kataras/iris/v12"
	"gomq/app/authorizer"
	"gomq/app/errs"
)

// AuthorizeMiddleware verify user json web token, Return unauthorized if
// fail to verify.
func AuthorizeMiddleware(i iris.Context) {
	var (
		auth           = authorizer.New()
		authentication *authorizer.Authentication
		ctx            context.Context
		err            error
		token          = auth.GetHeaderToken(i)
	)

	// Inherit request context for the same tracing.
	if span, ok := i.Values().Get(middlewares.TracingSpan).(log.Span); ok {
		ctx = span.GetContext()
	} else {
		ctx = i.Request().Context()
	}

	// Return http/401 (Unauthorized) if jwt not specified by header.
	if token == "" {
		log.Infofc(ctx, `[middleware=authorize] jwt not specified by header`)
		_ = i.JSON(result.New().WithError(errs.ErrUserUnauthorized))
		return
	}

	// Return http/401 (Unauthorized) if jwt verify failed.
	if authentication, err = auth.Verify(token); err != nil {
		log.Infofc(ctx, `[middleware=authorize] jwt not verified`)
		_ = i.JSON(result.New().WithError(errs.ErrUserInvalidAuthorization))
		return
	}

	// Set authentication to context and remove it when done.
	log.Infofc(ctx, `[middleware=authorize] jwt verified: token="%s"`, token)
	auth.Set(i, authentication)
	defer auth.Unset(i)
	i.Next()
}
